package mypackage;


import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 手机号工具类
 */
public class PhoneNumberUtil {
    //手机号开头必须为130-139,145,147,148,150-153,155-159,166,170,171,173,175,178,180-189,198,199，以后可添加
    private static final String phoneRegex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
    //没必要每次匹配生成一个新的对象
    private static final Pattern phonePattern = Pattern.compile(phoneRegex);

    /**
     * 判断是否是手机号
     *
     * @param phone 字符串类型的手机号
     * @return 结果
     */
    public static boolean isPhone(String phone) {
        if (StringUtils.isEmpty(phone) || phone.length() != 11) {
            return false;
        } else {
            Matcher m = phonePattern.matcher(phone);
            return m.matches();
        }
    }

    /**
     * 手机号打码
     *
     * @param phone 手机号
     * @return 打码手机号
     */
    public static String mosaicPhone(String phone) {
        if (StringUtils.isEmpty(phone) || phone.length() != 11) {
            return phone;
        } else {
            return phone.substring(0, 3) + "****" + phone.substring(7, 11);
        }
    }

    public static void main(String[] args) {
        String phone = "11111111111";
        boolean phone1 = isPhone(phone);
        System.out.println("phone1 = " + phone1);
    }
}


